package com.example.bankseckill.interceptor;


import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.bankseckill.Validator.Role;
import com.example.bankseckill.exception.GlobalException;
import com.example.bankseckill.pojo.vo.RespBeanEnum;
import com.example.bankseckill.utils.JWTUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * jwt 验证过滤器 验证token
 * @author lyj
 */
@Configuration
public class JWTInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        try {
            JWTUtils.verify(token);
        } catch (TokenExpiredException e) {
            throw new GlobalException(RespBeanEnum.TOKEN_EXPIRED);
        } catch (SignatureVerificationException e){
            throw new GlobalException(RespBeanEnum.TOKEN_ERROR);
        } catch (AlgorithmMismatchException e){
            throw new GlobalException(RespBeanEnum.TOKEN_ALGORITH);
        } catch (NullPointerException e) {
            throw new GlobalException(RespBeanEnum.TOKEN_EMPTY);
        }
        catch (Exception e) {
            throw new GlobalException(RespBeanEnum.TOKEN_LOGIN_EMPTY);
        }

        //判断该方法的访问权限，角色的权限能否访问
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        //获取方法
        Method method = handlerMethod.getMethod();
        //判断方法上是否有role注解
        Role role = method.getAnnotation(Role.class);
        //如果有
        if(role!=null){
            //角色等级
            Integer admin = JWTUtils.getAdminByToken(token);
            if(admin>=role.value()){
                return true;
            }else {
                throw new GlobalException(RespBeanEnum.ADMIN_INVAILD_LOGIN);
            }
        }
        return true;
    }
}
